<?php

namespace app\index\controller;

use think\facade\Db;
use think\facade\Request;
use think\facade\Session;

class Address
{
    /**
     * 新增地址
     * @return string|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function add()
    {
        if (Request::method() == "POST"){
            $all = Request::param();
            $all['user_id'] = Session::get("id");
            $all["is_delete"] = 1;
            $all['add_time'] = $all["up_time"] = time();
            $insert = Db::table("shop_address")->insert($all);
            if($insert){  //成功
                echo json_encode(['code'=>0,'msg'=>'添加成功']);
                exit;
            }else{  //失败
                echo json_encode(['code'=>1,'msg'=>'添加失败']);
                exit;
            }
        }else{
            $uid = Session::get("id");
            $address = Db::table("shop_address")->where("user_id",$uid)->select();
        }
        MyViewAssign([
            "address" => $address,
        ]);
        return MyView();
    }

    /**
     * 地址修改
     * @return string|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function edit()
    {
        if (Request::method() == "POST"){
            $all = Request::param();
            $all['user_id'] = Session::get("id");
            $all["is_delete"] = 1;
            $all["up_time"] = time();
            $update = Db::table("shop_address")->where("id",$all["id"])->update($all);
            if($update){  //成功
                echo json_encode(['code'=>0,'msg'=>'更新成功']);
                exit;
            }else{  //失败
                echo json_encode(['code'=>1,'msg'=>'更新失败']);
                exit;
            }
        }else{
            $id = Request::param("id");
            $address = Db::table("shop_address")->where("id",$id)->find();
        }
        MyViewAssign([
            "address" => $address,
        ]);
        return MyView();
    }

    /**
     * 删除收货地址
     * @throws \think\db\exception\DbException
     */
    public function del()
    {
        if (Request::method() == "POST"){
            $id = Request::param("id");
            $result = Db::table("shop_address")->where("id",$id)->delete();
            if($result){  //成功
                echo json_encode(['code'=>0,'msg'=>'删除成功']);
                exit;
            }else{  //失败
                echo json_encode(['code'=>1,'msg'=>'删除失败']);
                exit;
            }
        }
    }
}